﻿using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Threading.Tasks;
using TextNovelReader.Services;

namespace TextNovelReader.Model;

/// <summary>
/// MainPage 的视图模型。
/// </summary>
public partial class MainPageViewModel : ObservableObject
{
    private string _displayText = string.Empty;
    private Chapter _selectedChaptr = new(string.Empty, string.Empty, 0); 

    public string DisplayText
    {
        get => _displayText;
        set => SetProperty(ref _displayText, value); 
    }

    public ObservableCollection<Chapter> BookChapters { get; } = [];

    public async Task GetChaptersFromFileAsync(string filePath)
    {
        if (!File.Exists(filePath))
        {
            GlobalServices.Settings.FilePath = string.Empty;
            GlobalServices.Settings.ChapterIndex = 0;
            return; 
        }

        ChapterManager manager = new(filePath);
        var chapters = await manager.GetChaptersAsync();

        BookChapters.Clear(); 
        foreach (Chapter chapter in chapters)
        {
            BookChapters.Add(chapter); 
        }
    }

    public void OnWhiteLinesChanged(int whiteLines)
    {
        DisplayText = AddWhiteLines(_selectedChaptr.Text, whiteLines);
    }

    public void UpdateSelectedChapter(Chapter chapter)
    {
        _selectedChaptr = chapter; 
        GlobalServices.Events.RaiseTitleChanged(chapter.Title); 
        DisplayText = AddWhiteLines(_selectedChaptr.Text, GlobalServices.Settings.WhiteLines);
        GlobalServices.Settings.ChapterIndex = chapter.Index; 
    }

    private static string AddWhiteLines(string input, int whiteLines)
    {
        if (string.IsNullOrEmpty(input) || whiteLines == 0)
            return input;

        string[] lines = input.Split(Environment.NewLine);
        string seperator = Environment.NewLine;
        for (int i = 0; i < whiteLines; ++i)
            seperator += Environment.NewLine;
        return string.Join(seperator, lines); 
    }
}
